package com.ms.teapuesto.util;

import com.ms.teapuesto.LogServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * User: RAC
 * Date: 19/04/12
 */
public class ZipUtil {

    private static int BUFFER = 2156;
    public static final Logger LOG = LoggerFactory.getLogger(ZipUtil.class);

    public static File crearZip(File result, String zipName) {

        try {
            File resultZip = FileUtil.createTempFile(zipName + ".ZIP");
            BufferedInputStream origin = null;
            FileOutputStream dest = new
                    FileOutputStream(resultZip);
            ZipOutputStream out = new ZipOutputStream(new
                    BufferedOutputStream(dest));
            byte data[] = new byte[BUFFER];
            FileInputStream fi = new
                    FileInputStream(result);
            origin = new
                    BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(zipName + ".XML");
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0,
                    BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
            out.close();
            fi.close();
            return resultZip;
        } catch (Exception e) {
            LogServer.log.error("CREAR ZIP", e);
        }
        return null;
    }

    public static File extractZip(File fileResponse) {
        File result = null;
        BufferedInputStream bis = null;
        FileInputStream fis=null;
        FileOutputStream fos=null;
        BufferedOutputStream dest = null;
        try {
            result = FileUtil.createTempFile(".XML");
            fis = new FileInputStream(fileResponse);
            bis = new BufferedInputStream(fis);
            ZipInputStream zis = new
                    ZipInputStream(bis);
            ZipEntry entry;

            while ((entry = zis.getNextEntry()) != null) {
                int count;
                byte data[] = new byte[BUFFER];
                fos = new
                        FileOutputStream(result);
                dest = new
                        BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
            }
            return result;
        } catch (Exception e) {
            LogServer.log.error("Error en el sistema", e);
        } finally {
            FileUtil.close(bis);
            FileUtil.close(fis);
            FileUtil.close(dest);
            FileUtil.close(fos);
        }
        return result;
    }

}
